package own.stu.jobgib.playown.io.common;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 简单的自定义传输协议：前4个字节表示长度，后边字节为内容
 */
public class SimpleProtocol {

    protected InputStream inputStream_ = null;

    protected OutputStream outputStream_ = null;

    public SimpleProtocol(InputStream inputStream_, OutputStream outputStream_) {
        this.inputStream_ = inputStream_;
        this.outputStream_ = outputStream_;
    }

    public String read() throws IOException {
        byte[] bytes = new byte[4];
        int read = inputStream_.read(bytes);
        if (read <= 0) {
            return null;
        }
        int len = read32(bytes);
        byte[] data = new byte[len];
        read = inputStream_.read(data);
        if (read <= 0) {
            return "";
        }

        return new String(data);
    }

    public void write(String content) throws IOException {
        if (StringUtils.isBlank(content)) {
            return;
        }

        int len = content.getBytes().length;
        byte[] bytes = new byte[4];
        write32(bytes, len);

        outputStream_.write(bytes);
        outputStream_.write(content.getBytes());

        outputStream_.flush();
    }

    private static void write32(byte[] bytes, int i32) {
        assert bytes != null && bytes.length >= 4;

        bytes[0] = (byte) (0xff & (i32 >> 24));
        bytes[1] = (byte) (0xff & (i32 >> 16));
        bytes[2] = (byte) (0xff & (i32 >> 8));
        bytes[3] = (byte) (0xff & (i32 >> 0));
    }

    private int read32(byte[] buf) {
        int off = 0;
        return ((buf[off] & 0xff) << 24)
                | ((buf[off + 1] & 0xff) << 16)
                | ((buf[off + 2] & 0xff) << 8)
                | ((buf[off + 3] & 0xff));
    }
}
